# -*- encoding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
#    $Id$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields
from osv import osv
import wizard
import netsvc
import pooler
import time
from osv.orm import browse_record
from tools.misc import UpdateableStr,UpdateableDict

Fields=UpdateableDict()
Forms=UpdateableStr()

class wizard_create_payment_from_payment_term(wizard.interface):
    term_ids =[]
    def _update_payment_term_list(self, cr, uid, data, context):
        global term_ids
        
        cr.execute("""Select 
                        kcptl.id,
                        kptc.name||' '||kcptl.value_amount::text||' %%' as term_name
                    from 
                        kdvn_Contract_client kcc
                    left join
                        kderp_contract_payment_term_line kcptl on kcc.id = kcptl.contract_id
                    left join
                        kderp_payment_term_code kptc on term_id = kptc.id
                    left join
                        kdvn_payment_from_client kpfc on kcptl.id = kpfc.payment_term_line_id
                    where coalesce(kpfc.id,0)=0 and kcc.id =%d""" % data['id'])
        term_ids=[]
        list_term=''
        list_term="('"+str(0)+"','None')"
        first=True
        for id,term_name in cr.fetchall():
            if first:
                first = False
                list_term=list_term+",('"+str(-1)+"','All Term')"
            term_name=term_name.replace("'","\'")
            term_name=term_name.replace('"','\"')
            term_ids.append(id)
            list_term=list_term+",('"+str(id)+"','"+term_name+"')"
           
        list_term="["+list_term+"]"
        
        
        Fields['term_lists']={'string':'Payment Term','type':'selection','selection':eval(list_term),'default': lambda *a:'0'}
        
        Forms.string='''<?xml version="1.0"?>
                       <form string="Create New Payment from Client">
                               <separator string="Please choice payment term you want to create" colspan="4"/>
                               <field name="term_lists" required="1"/>
                       </form>'''
        return {}
    
    def _create_payment_from_client(self, cr, uid, data, context):
        #Status is Completed, Oustanding is None
        global term_ids
        try:
            chk_term =eval(data['form']['term_lists'])
        except:
            chk_term =data['form']['term_lists']
        ctc_id = data['id']
        #raise osv.except_osv("E",type(ctc_id))
        if chk_term<>0:
            if chk_term==-1:
                pooler.get_pool(cr.dbname).get('kdvn.contract.client')._create_payment_from_client(cr,uid,[ctc_id],{'term_ids':term_ids})
            else:
                pooler.get_pool(cr.dbname).get('kdvn.contract.client')._create_payment_from_client(cr,uid,[ctc_id],{'term_ids':[chk_term]})
        return {}
    
    states = {
        'init' : {
            'actions' : [_update_payment_term_list],
            'result' : {'type':'form','arch': Forms,'fields':Fields,
                        'state': [
                                  ('finish', '_Ok', 'gtk-ok', True),
                                  ('end', '_Cancel','gtk-cancel'),
                                  ]}},
        'finish': {
            'actions': [_create_payment_from_client],
            'result': {
                'type': 'state',
                'state': 'end'}},
            }
wizard_create_payment_from_payment_term('wizard_create_payment_from_payment_term')